import { PhaseTaskAdderComponent } from './../phase-task-adder/phase-task-adder.component';
import { PhasedTaskWithChildren } from './../../../model/task';
import { NzMessageService } from 'ng-zorro-antd/message';
import { PhasedTaskApiService } from './../../../api/phased-task-api.service';
import { NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-phase-task-add-page',
  templateUrl: './phase-task-add-page.component.html',
  styleUrls: ['./phase-task-add-page.component.less']
})
export class PhaseTaskAddPageComponent implements OnInit {

  treeNode: NzTreeNodeOptions[] = [];
  @ViewChild('taskAdder') taskAdder?: PhaseTaskAdderComponent;
  constructor(
    private taskApi: PhasedTaskApiService,
    private msg: NzMessageService
  ) { }

  ngOnInit(): void {
    this.fetchNode();
  }

  submit(): void {
    const inputData = this.taskAdder?.getData();
    if (inputData) {
      this.taskApi.create(inputData).subscribe(
        task => {
          this.msg.success('创建工作成功');
          this.cancle();
        },
        err => {
          this.msg.error('创建工作失败');
          console.error(err);
        }
      );
    }
  }

  cancle(): void {
    this.taskAdder?.reset();
  }

  private fetchNode(): void {
    this.taskApi.listWithChildren().subscribe(
      tasks => {
        this.treeNode = tasks.map(param => new PhasedTaskWithChildren(param).convertToNzTreeNodeOption());
      },
      err => {
        this.msg.error('获取工作选择菜单错误');
        console.error(err);
      }
    );
  }

}
